<template>
  <div class="search-form">
    <!-- 头部tab切换 -->
    <el-row type="flex" class="search-tab">
      <span
        v-for="(item, index) in tabs"
        :key="index"
        @click="handleSearchTab(item, index)"
        :class="{active: index === currentTab}"
      >
        <i :class="item.icon"></i>
        {{item.name}}
      </span>
    </el-row>

    <el-form class="search-form-content" ref="form" label-width="80px" :model="form">
      <el-form-item label="出发城市">
        <!-- fetch-suggestions：输入框文字变化时候就会触发，类似input事件 -->
        <!-- select: 选中下拉列表数据时候触发 -->
        <!-- trigger-on-focus设置要是获取输入框焦点后，要输入值后才显示下菜单 -->
        <el-autocomplete
          class="el-autocomplete"
          v-model="form.departCity"
          :fetch-suggestions="queryDepartSearch"
          placeholder="请搜索出发城市"
          :trigger-on-focus="false"
          @select="handleDepartSelect"
          @blur="handleDepartBlur"
        ></el-autocomplete>
      </el-form-item>

      <el-form-item label="到达城市">
        <el-autocomplete
          class="el-autocomplete"
          v-model="form.destCity"
          :fetch-suggestions="queryDestSearch"
          placeholder="请搜索到达城市"
          :trigger-on-focus="false"
          @select="handleDestSelect"
          @blur="handleDestBlur"
        ></el-autocomplete>
      </el-form-item>

      <el-form-item label="出发时间">
        <!-- @change="handleDate"用户选择时间的时候触发 -->
        <el-date-picker
          v-model="form.departDate"
          type="date"
          placeholder="请选择日期"
          style="width: 100%;"
          @change="handleDate"
        :picker-options="pickerOptions">
        ></el-date-picker>
      </el-form-item>

      <el-form-item label>
        <el-button style="width:100%;" type="primary" icon="el-icon-search" @click="handleSubmit">搜索</el-button>
      </el-form-item>
      <div class="reverse">
        <span @click="handleReverse">换</span>
      </div>
    </el-form>
  </div>
</template>


<script>
import moment from "moment";
export default {
  data() {
    return {
      tabs: [
        { icon: "iconfont icondancheng", name: "单程" },
        { icon: "iconfont iconshuangxiang", name: "往返" }
      ],
      currentTab: 0,
      form: {
        departCity: "",
        departCode: "",
        destCity: "",
        destCode: "",
        departDate: ""
      },

      // 城市列表
      newCities: [],
       // 禁用日期选中
      pickerOptions:{
           disabledDate(time) {
            return time.getTime() < Date.now() - 3600 * 1000 * 24;
          }
      }
    };
  },
  methods: {
    //   当用户输入城市不点击显示菜单的时候，我们要给出发城市输入框设置个一个默认值，一般就是设置显示菜单的第一项
    handleDepartBlur() {
      //   判断要是用户获取焦点，数组要是为空的时候，就不执行下面代码，不然不会报错
      if (this.newCities.length === 0) return;
      // console.log(this.destCities)
      this.form.departCity = this.newCities[0].value;
      this.form.departCode = this.newCities[0].sort;
    },
    //   当用户输入城市不点击显示菜单的时候，我们要给目标城市输入框设置个一个默认值，一般就是设置显示菜单的第一项
    handleDestBlur() {
      //   判断要是用户获取焦点，数组要是为空的时候，就不执行下面代码，不然不会报错
      if (this.newCities.length === 0) return;
      //    console.log(this.destCities)
      this.form.destCity = this.newCities[0].value;
      this.form.destCode = this.newCities[0].sort;
    },
    //   封装一个输入关键字可以提示是那些城市有这些字的
    getCities(value, cb) {
      // 如果输入框数据为空，返回空列表
      if (!value.trim()) {
        return cb([]);
      }
      this.$axios({
        url: "/airs/city",
        params: {
          name: value
        }
      }).then(res => {
        const { data } = res.data;
        this.newCities = data.map(item => {
          // 把城市名最后的市字去掉
          item.value = item.name.substr(0, item.name.length - 1);
          return item;
        });
        cb(this.newCities);
        // console.log(this.destCities);
      });
    },
    // 出发城市输入框的输入事件，根据输入的关键字请求接口返回相关城市。
    // value: 是输入框的值，发送给服务器，服务器根据和用户输入的关键字返回数据
    // cb：是回调函数，调用函数时候必须要传入一个数组
    // cb参数的数组的元素必须是一个对象，对面里面必须包含value值
    // cb参数的数组的元素 (必须是一个对象，对面里面必须包含value值)
    queryDepartSearch(value, cb) {
      this.getCities(value, cb);
    },
    // 出发城市下拉选择时触发
    // item: 选中的下拉列表的数据
    handleDepartSelect(item) {
      this.form.departCity = item.value;
      this.form.departCode = item.sort;
      //   console.log(item);
    },
    // 点击搜索，提交表单
    handleSubmit() {
      let valid = true;
      // 需要验证的表单字段
      const rules = [
        { value: this.form.departCity, message: "请输入出发城市" },
        { value: this.form.destCity, message: "请输入到达城市" },
        { value: this.form.departDate, message: "请选择出发时间" }
      ];
      // 循环遍历数组里面每一个项
      rules.forEach(item => {
        // 每循环一项，要是里面值为空的时候，就停止循环数组，提示用户，要输入那一项
        if (!valid) return;
        if (!item.value.trim()) {
          // 提示错误
          this.$confirm(item.message, "提示", {
            confirmButtonText: "确定",
            showCancelButton: false,
            type: "warning"
          });
          // 当输入为空或者不输入的时候，把valid值改为false
          valid = false;
        }
      });
      // console.log(rules);
      // 数据为空，停止上传表单
      if (!valid) return;
      // 保存到vuex的store中
      this.$store.commit('air/setHistory',this.form)
      // 正确的话就实现页面跳转
      this.$router.push({
        path: "/air/flights",
        query: this.form
      });

      // console.log(this.form);
    },
    // 达到城市下拉选择时触发
    // item: 选中的下拉列表的数据
    handleDestSelect(item) {
      this.form.destCity = item.value;
      this.form.destCode = item.sort;
    },
    // value是用户在input输入框输入的值
    // cb：是回调函数，调用函数时候必须要传入一个数组
    // cb参数的数组的元素必须是一个对象，对面里面必须包含value值
    // cb参数的数组的元素 (必须是一个对象，对面里面必须包含value值)
    queryDestSearch(value, cb) {
      this.getCities(value, cb);
    },
    // 确认选择日期时触发,valud是一个Date时间对象
    handleDate(value) {
      this.form.departDate = moment(value).format("YYYY-MM-DD");
    },
    // 触发和目标城市切换时触发
    handleReverse() {
      // 把form的出发城市和到达城市交叉赋值
      const { departCity, departCode, destCity, destCode } = this.form;

      this.form.departCity = destCity;
      this.form.departCode = destCode;

      this.form.destCity = departCity;
      this.form.destCode = departCode;
    },
    // 切换tab栏的往返触发
    handleSearchTab(item,index){
        if(index === 1){
            this.$alert("目前暂时不支持往返", "提示", {
                    type: "warning"
                })
        }
    }
  }
};
</script>

<style scoped lang="less">
.search-form {
  border: 1px #ddd solid;
  border-top: none;
  width: 360px;
  height: 350px;
  box-sizing: border-box;
}

.search-tab {
  span {
    display: block;
    flex: 1;
    text-align: center;
    height: 48px;
    line-height: 42px;
    box-sizing: border-box;
    border-top: 3px #eee solid;
    background: #eee;
  }

  .active {
    border-top-color: orange;
    background: #fff;
  }

  i {
    margin-right: 5px;
    font-size: 18px;

    &:first-child {
      font-size: 16px;
    }
  }
}

.search-form-content {
  padding: 15px 50px 15px 15px;
  position: relative;

  .el-autocomplete {
    width: 100%;
  }
}

.reverse {
  position: absolute;
  top: 35px;
  right: 15px;

  &:after,
  &:before {
    display: block;
    content: "";
    position: absolute;
    left: -35px;
    width: 25px;
    height: 1px;
    background: #ccc;
  }

  &:after {
    top: 0;
  }

  &:before {
    top: 60px;
  }

  span {
    display: block;
    position: absolute;
    top: 20px;
    right: 0;
    font-size: 12px;
    background: #999;
    color: #fff;
    width: 20px;
    height: 20px;
    line-height: 18px;
    text-align: center;
    border-radius: 2px;
    cursor: pointer;

    &:after,
    &:before {
      display: block;
      content: "";
      position: absolute;
      left: 10px;
      width: 1px;
      height: 20px;
      background: #ccc;
    }

    &:after {
      top: -20px;
    }

    &:before {
      top: 20px;
    }
  }
}
</style>
